﻿using UnityEngine;
using UnityEngine.UI;

namespace QFramework
{
    public class UIItemTip : MonoBehaviour
    {
        public GameObject TipPanel;
        public Image Icon;
        public Text Name;
        public Text Description;

        private static UIItemTip mInstance;
        #region runtime
        private void Awake()
        {
            mInstance = this;
        }
        private void Start()
        {
            mInstance.TipPanel.Hide();
        }
        private void OnDestroy()
        {
            mInstance = null;
        }
        #endregion

        public static void Show(UISlot slot)
        {
            if (slot.Data.Item != null)
            {
                mInstance.Icon.sprite = slot.Data.Item.GetIcon;
                mInstance.Name.text = slot.Data.Item.GetName;
                mInstance.Description.text = slot.Data.Item.GetDescription;
                mInstance.TipPanel.Show();

                var mousePos = Input.mousePosition;

                if (RectTransformUtility.ScreenPointToLocalPointInRectangle(mInstance.transform as RectTransform, mousePos, null, out var localPoint))
                {
                    const int offset = 40;
                    var mousePosToCenter = mousePos - new Vector3(Screen.width * 0.5f, Screen.height * 0.5f);
                    if (mousePosToCenter.x.Abs() > mousePosToCenter.y.Abs())
                    {
                        if (mousePosToCenter.x < 0)
                        {
                            mInstance.TipPanel.GetComponent<RectTransform>().pivot = new Vector2(0f, 0.5f);
                            mInstance.TipPanel.LocalPosition2D(localPoint + Vector2.right * offset);
                        }
                        else
                        {
                            mInstance.TipPanel.GetComponent<RectTransform>().pivot = new Vector2(1f, 0.5f);
                            mInstance.TipPanel.LocalPosition2D(localPoint + Vector2.left * offset);
                        }
                    }
                    else
                    {
                        if (mousePosToCenter.y < 0)
                        {
                            mInstance.TipPanel.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0f);
                            mInstance.TipPanel.LocalPosition2D(localPoint + Vector2.up * offset);
                        }
                        else
                        {
                            mInstance.TipPanel.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 1f);
                            mInstance.TipPanel.LocalPosition2D(localPoint + Vector2.down * offset);
                        }
                    }
                }
            }
        }
        public static void Hide()
        {
            mInstance.TipPanel.Hide();
        }
    }
}